import random

from flask import request, jsonify

from apps.apis import api
from apps.core.auth import verify_token_auth
from apps.core.database import db
from apps.models import SubDb, UpdateMeta, UpdateRef, CountSubdbYearMeta, CountSubDbYearRef
from apps.utils.return_info import ReturnInfo


@api.route("/test/add_data", methods=['POST'])
@verify_token_auth(allowtokennull=True)
def add_data():
    """
    添加虚拟的测试数据，方便展示前端效果
    ---
    tags:
      - test
    parameters:
      - in: body
        name: body
        required: true
        description: JSON 参数.
        schema:
          properties:
            token:
              type: string
              description: 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
              example: ''
            subdb:
              type: object
              description: 字库表
              example: {"sub_db_id":"99999","product":"VIPTEST","sub_db":"TEST","sub_db_name":"维普测试数据","zt_provider":"viptestdata","provider":"VIPTEST","url":"http://192.168.31.209:8081/","summary":"维普测试数据,http://192.168.31.209:8081/"}
            update_meta:
              type: object
              description: 题录更新数据表
              example: {"sub_db_id":"99999","count_submit":33573255,"count_update":0,"count_create":33573255,"count_deprecated":0,"count_delete":0,"count_meta":33573255,"update_time":"2019-12-16 08:37:14"}
            update_ref:
              type: object
              description: 引文更新数据表
              example: {"sub_db_id":"99999","count_submit":"12940327","count_update":"0","count_create":"12940327","count_deprecated":"0","count_delete":"0","count_ref":"12967483","update_time":"2019-12-16 08:37:14"}
            count_subdb_year_meta:
              type: object
              description: 题录年统计数据表
              example: {"sub_db_id":"99999","update_time":"2019-12-16 08:37:14","count_json":{"msg": [{"cnt": 2642549, "pub_year": "2019"}, {"cnt": 3534266, "pub_year": "2015"}, {"cnt": 3486621, "pub_year": "2017"}, {"cnt": 3420631, "pub_year": "2018"}, {"cnt": 3226500, "pub_year": "2010"}, {"cnt": 3300697, "pub_year": "2011"}, {"cnt": 3542591, "pub_year": "2014"}, {"cnt": 3396757, "pub_year": "2012"}, {"cnt": 3535710, "pub_year": "2016"}, {"cnt": 3486933, "pub_year": "2013"}]}}
            count_subdb_year_ref:
              type: object
              description: 引文年统计数据表
              example: {"sub_db_id":"99999","update_time":"2019-12-16 08:37:14","count_json":{"msg": [{"cnt": 19039808, "cited_pub_year": "2017"}, {"cnt": 19408295, "cited_pub_year": "2018"}, {"cnt": 16312297, "cited_pub_year": "2019"}, {"cnt": 17909798, "cited_pub_year": "2016"}, {"cnt": 18488, "cited_pub_year": "2020"}, {"cnt": 16735878, "cited_pub_year": "2015"}]}}
    definitions:
      ReturnInfoTest:
        type: object
        properties:
          msg_code:
            type: string
            description: SUCCESS 或者 FAILED.
            example: SUCCESS
          msg:
            type: string
            description: 说明文字，帮助找到失败原因
            example: 不能使用get请求
          data:
            type: string
            description: 空 ""
    consumes:
      - application/json
    produces:
      - application/json

    responses:
      200:
        description: OK.
        schema:
          $ref: '#/definitions/ReturnInfoTest'
        examples:
          returninfo: {"msg_code":"SUCCESS","msg":"成功","data":""}
    :return:
    """
    ret_obj = ReturnInfo()
    jsons = request.json

    subdb_data = jsons.get("subdb")
    if subdb_data:
        subDb = SubDb(**subdb_data)
        try:
            db.session.add(subDb)
            db.session.commit()
        except Exception as e:
            ret_obj.msg_code = "FAILED"
            ret_obj.msg = "SubDb库插入数据库失败"
            ret_obj.data = {"errmsg": str(e)}
            return jsonify(ret_obj.todict())
    update_meta = jsons.get("update_meta")
    if update_meta:
        sub_db_id = update_meta["sub_db_id"]
        updateMeta = UpdateMeta.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateMeta.update_time.desc()).first()
        if updateMeta:
            update_meta["count_meta"] = updateMeta.count_meta + update_meta["count_create"] - update_meta[
                "count_delete"]

        updateMeta = UpdateMeta(**update_meta)
        try:
            db.session.add(updateMeta)
            db.session.commit()
        except Exception as e:
            ret_obj.msg_code = "FAILED"
            ret_obj.msg = "updateMeta库插入数据库失败"
            ret_obj.data = {"errmsg": str(e)}
            return jsonify(ret_obj.todict())
    update_ref = jsons.get("update_ref")
    if update_ref:
        sub_db_id = update_ref["sub_db_id"]
        updateRef = UpdateRef.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateRef.update_time.desc()).first()
        if updateRef:
            update_ref["count_ref"] = str(int(updateRef.count_ref) + int(update_ref["count_create"]) - int(update_ref[
                                                                                                               "count_delete"]))

        updateRef = UpdateRef(**update_ref)
        try:
            db.session.add(updateRef)
            db.session.commit()
        except Exception as e:
            ret_obj.msg_code = "FAILED"
            ret_obj.msg = "updateMeta库插入数据库失败"
            ret_obj.data = {"errmsg": str(e)}
            return jsonify(ret_obj.todict())
    count_subdb_year_meta = jsons.get("count_subdb_year_meta")
    if count_subdb_year_meta:
        if update_meta:
            sub_db_id = count_subdb_year_meta["sub_db_id"]
            updateMeta = UpdateMeta.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateMeta.update_time.desc()).first()
            if updateMeta:
                allcount = 0
                i = 0
                for item in count_subdb_year_meta["count_json"]["msg"]:
                    i = i + 1
                    allcount = allcount + item["cnt"]
                if allcount != updateMeta.count_meta:
                    count = allcount - updateMeta.count_meta
                    remainder = count % i
                    result = (count - remainder) // i
                    j = 0
                    for num in range(i):
                        j = j + 1
                        if j <= abs(remainder):
                            one = remainder // abs(remainder)
                        else:
                            one = 0
                        count_subdb_year_meta["count_json"]["msg"][num]["cnt"] = \
                            count_subdb_year_meta["count_json"]["msg"][num]["cnt"] - result + one

        count_subdb_year_meta = CountSubdbYearMeta(**count_subdb_year_meta)
        try:
            db.session.add(count_subdb_year_meta)
            db.session.commit()
        except Exception as e:
            ret_obj.msg_code = "FAILED"
            ret_obj.msg = "count_subdb_year_meta库插入数据库失败"
            ret_obj.data = {"errmsg": str(e)}
            return jsonify(ret_obj.todict())
    count_subdb_year_ref = jsons.get("count_subdb_year_ref")
    if count_subdb_year_ref:
        sub_db_id = count_subdb_year_ref["sub_db_id"]
        updateRef = UpdateRef.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateRef.update_time.desc()).first()
        if updateRef:
            allcount = 0
            i = 0
            for item in count_subdb_year_ref["count_json"]["msg"]:
                i = i + 1
                allcount = allcount + item["cnt"]
            if allcount != updateRef.count_ref:
                count = allcount - int(updateRef.count_ref)
                remainder = count % i
                result = (count - remainder) // i
                j = 0
                for num in range(i):
                    j = j + 1
                    if j <= abs(remainder):
                        one = remainder // abs(remainder)
                    else:
                        one = 0
                    count_subdb_year_ref["count_json"]["msg"][num]["cnt"] = \
                        count_subdb_year_ref["count_json"]["msg"][num]["cnt"] - result + one

        count_subdb_year_ref = CountSubDbYearRef(**count_subdb_year_ref)
        try:
            db.session.add(count_subdb_year_ref)
            db.session.commit()
        except Exception as e:
            ret_obj.msg_code = "FAILED"
            ret_obj.msg = "count_subdb_year_ref库插入数据库失败"
            ret_obj.data = {"errmsg": str(e)}
            return jsonify(ret_obj.todict())

    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "添加成功"
    return jsonify(ret_obj.todict())


@api.route("/test/add_all_data", methods=['POST'])
@verify_token_auth(allowtokennull=True)
def add_all_data():
    """
       添加虚拟的测试数据，方便展示前端效果
       ---
       tags:
         - test
       parameters:
         - in: body
           name: body
           required: true
           description: JSON 参数.
           schema:
             properties:
               token:
                 type: string
                 description: 用户认证. 为空被当作游客,将不认证 空为 "" (空字符串)
                 example: ''
               subdb:
                 type: object
                 description: 字库表
                 example: {"sub_db_id":"99999","product":"VIPTEST","sub_db":"TEST","sub_db_name":"维普测试数据","zt_provider":"viptestdata","provider":"VIPTEST","url":"http://192.168.31.209:8081/","summary":"维普测试数据,http://192.168.31.209:8081/"}
               update_meta:
                 type: object
                 description: 题录更新数据表
                 example: {"sub_db_id":"99999","count_submit":3003255,"count_update":0,"count_create":3003255,"count_deprecated":0,"count_delete":0,"count_meta":3003255,"update_time":"2019-12-16 08:37:14"}
               update_ref:
                 type: object
                 description: 引文更新数据表
                 example: {"sub_db_id":"99999","count_submit":"3000327","count_update":"0","count_create":"3000327","count_deprecated":"0","count_delete":"0","count_ref":"3000327","update_time":"2019-12-16 08:37:14"}
               count_subdb_year_meta:
                 type: object
                 description: 题录年统计数据表
                 example: {"sub_db_id":"99999","update_time":"2019-12-16 08:37:14","count_json":{"msg": [{"cnt": 1012549, "pub_year": "2019"}, {"cnt": 504266, "pub_year": "2015"}, {"cnt": 706621, "pub_year": "2017"}, {"cnt": 80631, "pub_year": "2018"}, {"cnt": 106500, "pub_year": "2010"}, {"cnt": 200697, "pub_year": "2011"}, {"cnt": 502591, "pub_year": "2014"}, {"cnt": 306757, "pub_year": "2012"}, {"cnt": 505710, "pub_year": "2016"}, {"cnt": 806933, "pub_year": "2013"}]}}
               count_subdb_year_ref:
                 type: object
                 description: 引文年统计数据表
                 example: {"sub_db_id":"99999","update_time":"2019-12-16 08:37:14","count_json":{"msg": [{"cnt": 1019808, "cited_pub_year": "2019"}, {"cnt": 508295, "cited_pub_year": "2015"}, {"cnt": 702297, "cited_pub_year": "2017"}, {"cnt": 89798, "cited_pub_year": "2018"}, {"cnt": 108488, "cited_pub_year": "2010"}, {"cnt": 105878, "cited_pub_year": "2011"}, {"cnt": 502591, "cited_pub_year": "2014"}, {"cnt": 306757, "cited_pub_year": "2012"}, {"cnt": 505710, "cited_pub_year": "2016"}, {"cnt": 806933, "cited_pub_year": "2013"}]}}
       definitions:
         ReturnInfoTest:
           type: object
           properties:
             msg_code:
               type: string
               description: SUCCESS 或者 FAILED.
               example: SUCCESS
             msg:
               type: string
               description: 说明文字，帮助找到失败原因
               example: 不能使用get请求
             data:
               type: string
               description: 空 ""
       consumes:
         - application/json
       produces:
         - application/json

       responses:
         200:
           description: OK.
           schema:
             $ref: '#/definitions/ReturnInfoTest'
           examples:
             returninfo: {"msg_code":"SUCCESS","msg":"成功","data":""}
       :return:
       """
    ret_obj = ReturnInfo()
    jsons = request.json
    list_time = ["2019-10-25 02:17:44", "2019-11-01 05:30:00", "2019-11-08 05:32:14", "2019-11-14 05:33:39",
                 "2019-11-19 05:35:04", "2019-11-25 05:35:41", "2019-12-01 05:35:53", "2019-12-05 05:36:24",
                 "2019-12-10 05:36:43", "2019-12-18 05:36:57"]
    for i in range(10):

        meta_count_submit = random.sample(range(5000000, 10000000), 1)
        meta_count_submit = meta_count_submit[0]
        jsons["update_meta"]["count_submit"] = meta_count_submit
        jsons["update_meta"]["count_create"] = meta_count_submit
        jsons["update_meta"]["count_meta"] = meta_count_submit
        ref_count_submit = random.sample(range(0, 10000000), 1)
        ref_count_submit = ref_count_submit[0]
        jsons["update_ref"]["count_submit"] = ref_count_submit
        jsons["update_ref"]["count_create"] = str(ref_count_submit)
        jsons["update_ref"]["count_ref"] = str(ref_count_submit)
        jsons["update_meta"]["update_time"] = list_time[i]
        jsons["update_ref"]["update_time"] = list_time[i]
        jsons["count_subdb_year_meta"]["update_time"] = list_time[i]
        jsons["count_subdb_year_ref"]["update_time"] = list_time[i]
        jsons["update_meta"]["create_time"] = list_time[i]
        jsons["update_ref"]["create_time"] = list_time[i]
        jsons["count_subdb_year_meta"]["create_time"] = list_time[i]
        jsons["count_subdb_year_ref"]["create_time"] = list_time[i]
        subdb_data = jsons.get("subdb")
        if subdb_data:
            subDb = SubDb.query.filter_by(sub_db_id=subdb_data["sub_db_id"]).first()
            if not subDb:
                subDb = SubDb(**subdb_data)
                try:
                    db.session.add(subDb)
                    db.session.commit()
                except Exception as e:
                    ret_obj.msg_code = "FAILED"
                    ret_obj.msg = "SubDb库插入数据库失败"
                    ret_obj.data = {"errmsg": str(e)}
                    return jsonify(ret_obj.todict())
        update_meta = jsons.get("update_meta")
        if update_meta:
            sub_db_id = update_meta["sub_db_id"]
            updateMeta = UpdateMeta.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateMeta.update_time.desc()).first()
            if updateMeta:
                update_meta["count_meta"] = updateMeta.count_meta + update_meta["count_create"] - update_meta[
                    "count_delete"]

            updateMeta = UpdateMeta(**update_meta)
            try:
                db.session.add(updateMeta)
                db.session.commit()
            except Exception as e:
                ret_obj.msg_code = "FAILED"
                ret_obj.msg = "updateMeta库插入数据库失败"
                ret_obj.data = {"errmsg": str(e)}
                return jsonify(ret_obj.todict())
        update_ref = jsons.get("update_ref")
        if update_ref:
            sub_db_id = update_ref["sub_db_id"]
            updateRef = UpdateRef.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateRef.update_time.desc()).first()
            if updateRef:
                update_ref["count_ref"] = str(
                    int(updateRef.count_ref) + int(update_ref["count_create"]) - int(update_ref[
                                                                                         "count_delete"]))

            updateRef = UpdateRef(**update_ref)
            try:
                db.session.add(updateRef)
                db.session.commit()
            except Exception as e:
                ret_obj.msg_code = "FAILED"
                ret_obj.msg = "updateMeta库插入数据库失败"
                ret_obj.data = {"errmsg": str(e)}
                return jsonify(ret_obj.todict())
        count_subdb_year_meta = jsons.get("count_subdb_year_meta")
        if count_subdb_year_meta:
            if update_meta:
                sub_db_id = count_subdb_year_meta["sub_db_id"]
                updateMeta = UpdateMeta.query.filter_by(sub_db_id=sub_db_id).order_by(
                    UpdateMeta.update_time.desc()).first()
                if updateMeta:
                    allcount = 0
                    i = 0
                    for item in count_subdb_year_meta["count_json"]["msg"]:
                        i = i + 1
                        allcount = allcount + item["cnt"]
                    if allcount != updateMeta.count_meta:
                        count = allcount - updateMeta.count_meta
                        remainder = count % i
                        result = (count - remainder) // i
                        j = 0
                        for num in range(i):
                            j = j + 1
                            if j <= abs(remainder):
                                one = remainder // abs(remainder)
                            else:
                                one = 0
                            count_subdb_year_meta["count_json"]["msg"][num]["cnt"] = \
                                count_subdb_year_meta["count_json"]["msg"][num]["cnt"] - result + one

            count_subdb_year_meta = CountSubdbYearMeta(**count_subdb_year_meta)
            try:
                db.session.add(count_subdb_year_meta)
                db.session.commit()
            except Exception as e:
                ret_obj.msg_code = "FAILED"
                ret_obj.msg = "count_subdb_year_meta库插入数据库失败"
                ret_obj.data = {"errmsg": str(e)}
                return jsonify(ret_obj.todict())
        count_subdb_year_ref = jsons.get("count_subdb_year_ref")
        if count_subdb_year_ref:
            sub_db_id = count_subdb_year_ref["sub_db_id"]
            updateRef = UpdateRef.query.filter_by(sub_db_id=sub_db_id).order_by(UpdateRef.update_time.desc()).first()
            if updateRef:
                allcount = 0
                i = 0
                for item in count_subdb_year_ref["count_json"]["msg"]:
                    i = i + 1
                    allcount = allcount + item["cnt"]
                if allcount != updateRef.count_ref:
                    count = allcount - int(updateRef.count_ref)
                    remainder = count % i
                    result = (count - remainder) // i
                    j = 0
                    for num in range(i):
                        j = j + 1
                        if j <= abs(remainder):
                            one = remainder // abs(remainder)
                        else:
                            one = 0
                        count_subdb_year_ref["count_json"]["msg"][num]["cnt"] = \
                            count_subdb_year_ref["count_json"]["msg"][num]["cnt"] - result + one

            count_subdb_year_ref = CountSubDbYearRef(**count_subdb_year_ref)
            try:
                db.session.add(count_subdb_year_ref)
                db.session.commit()
            except Exception as e:
                ret_obj.msg_code = "FAILED"
                ret_obj.msg = "count_subdb_year_ref库插入数据库失败"
                ret_obj.data = {"errmsg": str(e)}
                return jsonify(ret_obj.todict())

    ret_obj.msg_code = "SUCCESS"
    ret_obj.msg = "添加成功"
    return jsonify(ret_obj.todict())
